package com.matt.service.impl;

import com.matt.domain.LiveRoomRecord;
import com.matt.foundation.utils.DateUtil;
import com.matt.repository.LiveRoomRecordRepository;
import com.matt.service.LiveRoomRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Describle This Class Is 直播时长统计
 * @Author ZengMin
 * @Date 2018/11/1 17:07
 * @Company Matt
 */
@Service
public class LiveRoomRecordServiceImpl implements LiveRoomRecordService {

    private static final long START_TIME = 10;  //初始值 10秒

    @Autowired
    LiveRoomRecordRepository liveRoomRecordRepository;

    @Transactional
    @Override
    public boolean updateLiveTime(String userId, String clientId, String liveId, String requestIpAddr) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = simpleDateFormat.format(new Date());
        LiveRoomRecord liveRoomRecords = liveRoomRecordRepository.findByUserIdAndLiveRoomIdAndDate(userId, liveId, DateUtil.parseToDate(date));
        if(liveRoomRecords != null){
            long time = liveRoomRecords.getTime();
            liveRoomRecords.setTime(time+=START_TIME);
            liveRoomRecords.setClientId(clientId);
        }else{
            liveRoomRecords = new LiveRoomRecord();
            liveRoomRecords.setClientId(clientId);
            liveRoomRecords.setTime(START_TIME);
            liveRoomRecords.setLiveRoomId(liveId);
            liveRoomRecords.setDate(new Date());
            liveRoomRecords.setUserId(userId);
            liveRoomRecords.setIp(requestIpAddr);
        }
        liveRoomRecords.setLastModify(new Date());
        LiveRoomRecord liveRoomRecord = liveRoomRecordRepository.saveAndFlush(liveRoomRecords);
        return liveRoomRecord!=null;
    }
}
